package com.pym.Contoller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pym.Contoller.Utils.R;
import com.pym.Service.BookService;
import com.pym.pojo.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/Books")
public class BookController {

    @Autowired
    private BookService bookService;

   @GetMapping
    public R findBookAll(){
      return  new R(true,bookService.findBookAll()) ;
    }

    @PostMapping
    public R sava(@RequestBody Book book){
        boolean insert = bookService.insert(book);
        return new R(insert,insert ? "增加成功":"增加失败");
    }

    @GetMapping("{id}")
    public R finBookAllById(@PathVariable int id){
     return new R(true,bookService.selectByPrimaryKey(id));
    }

    @DeleteMapping("{id}")
    public R finBookByID(@PathVariable int id){
     return new R(bookService.deleteByPrimaryKey(id));
    }
      @PutMapping
        public R UpdateBookById(@RequestBody Book book){
     return new R(bookService.updateByPrimaryKeySelective(book));
      }

//      @GetMapping("{currentPage}/{pageSize}")
//    public R finBooAllByCurrentPageAndPageSize(@PathVariable(required = false) int currentPage,@PathVariable(required = false) int pageSize){
//          PageInfo<Book> bookPageInfo = bookService.finBooAllByCurrentPageAndPageSize(currentPage, pageSize);
//          //进行删除的时候如果闪掉最后返回的还是当前页的进行判断
//          if (currentPage>bookPageInfo.getPageSize()){
//            bookPageInfo=bookService.finBooAllByCurrentPageAndPageSize(bookPageInfo.getPageSize(),pageSize);
//          }
//          return new R(true,bookPageInfo);
//
//      }

    @GetMapping("{currentPage}/{pageSize}")
    public R finBooAllByCurrentPageAndPageSize(@PathVariable(required = false) int currentPage,@PathVariable(required = false) int pageSize,Book book){
        PageHelper.startPage(currentPage,pageSize);
        List<Book> books = bookService.finBooAllByCurrentPageAndPageSizeAndBook(book);
        PageInfo<Book> bookPageInfo = new PageInfo<>(books);
        //进行删除的时候如果闪掉最后返回的还是当前页的进行判断
        return new R(true,bookPageInfo);

    }
}
